package com.wlx.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wlx.common.core.constant.Constants;
import com.wlx.common.core.exception.CaptchaException;
import com.wlx.common.core.utils.StringUtils;
import com.wlx.common.core.web.domain.AjaxResult;
import com.wlx.common.redis.service.RedisService;
import com.wlx.gateway.config.properties.IgnoreWhiteProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 验证码过滤器
 *
 * @author wlx
 */
@Component
public class SendCodeFilter extends AbstractGatewayFilterFactory<Object> {
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;

    @Autowired
    private RedisService redisService;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String url = request.getURI().getPath();
            // 非登录请求，不处理
            if (!StringUtils.matches(url, ignoreWhite.getSendFilters())) {
                return chain.filter(exchange);
            }

            try {
                String rspStr = resolveBodyFromRequest(request);
                JSONObject obj = JSONObject.parseObject(rspStr);
                String code = obj.getString("code");
                String receiver = obj.getString("receiver");
                String appId = obj.getString("appId");

                if (StringUtils.isBlank(code)) {
                    throw new CaptchaException("验证码不能为空");
                }

                if (StringUtils.isBlank(receiver)) {
                    throw new CaptchaException("接收者已失效");
                }

                if (StringUtils.isBlank(appId)) {
                    throw new CaptchaException("应用ID不能为空");
                }

                String verifyKey = Constants.RECEIVER_CODE_KEY + appId + ":" + receiver;
                String captcha = redisService.getCacheObject(verifyKey);
                redisService.deleteObject(verifyKey);
                if (!code.equalsIgnoreCase(captcha)) {
                    throw new CaptchaException("验证码错误");
                }
            } catch (Exception e) {
                ServerHttpResponse response = exchange.getResponse();
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return exchange.getResponse().writeWith(
                        Mono.just(response.bufferFactory().wrap(JSON.toJSONBytes(AjaxResult.error(e.getMessage())))));
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
